package com.wyiot.core.api;

import com.wyiot.core.exception.ValidateException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

/**
 * 分组校验Aop
 */

@Aspect
@Component
public class FormValidationAspect {
    @Around("execution(public * com..controller.*.*(..,org.springframework.validation.BindingResult))")
    public Object checkBindingResult(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs(); //获取连接点的形参
        BindingResult bresult = (BindingResult)args[args.length-1];//获取形参中的最后一个参数
        if(bresult.hasErrors()){
            ObjectError error = bresult.getFieldErrors().get(0);
      /*      if (error == null){
                error = bresult.getAllErrors().get(0);
            }*/
            throw ValidateException.of(error.getDefaultMessage());
        }else {
            return joinPoint.proceed(args);
        }
    }
}
